#include "window.h"
#include "components/view.h"
#include "layout/layout_power_manager.h"
#include <spdlog/spdlog.h>
#include <cassert>

Window::Window()
	: _views(), _active_view_index(-1),
	  _layout_manager(this) {
	_window_area.cols = COLS;
	_window_area.lines = LINES;
	create_view(LayoutMode::Auto);
}

std::shared_ptr<View> Window::get_active_view(){
	if (_active_view_index == -1) {
		if (_views.size() > 0) {
			_active_view_index = 0;
		} else {
			return nullptr;
		}
	}
	return _views[_active_view_index];
}
void Window::update() {
	for (auto &&v : _views) {
		v->update();
	}
	get_active_view()->update();
	doupdate();
}

void Window::update_all()
{
	spdlog::info("Window::update_all()");
	timeout(0);
	getch();
	timeout(-1);
	update_window_size();
	update_window_size();
	update_window_size();
	_layout_manager.update_layout();
	update();
}

void Window::next_view() {
	if (_active_view_index < _views.size() - 1) {
		_active_view_index++;
	}
}

void Window::prev_view() {
	if (_active_view_index > 0) {
		_active_view_index--;
	}
}

void Window::create_view(LayoutMode mode, bool active, std::shared_ptr<Buffer> buffer) {
	_views.push_back(std::make_shared<View>(this, Rect {0}, buffer));
	_layout_manager.add(_views.back(), mode);
	_layout_manager.update_layout();
	if (active) {
		_active_view_index = _views.size() - 1;
	}
}

void Window::key_input_event(type::input_type ch) {
	switch (ch) {
	case KEY_F(1):
		_status = WindowStatus::EXIT;
		break;
	case KEY_F(2):
		next_view();
		break;
	case KEY_F(3):
		prev_view();
		break;
	case KEY_F(4):
		create_view(LayoutMode::Vertical, true);
		break;
	case KEY_F(5):
		create_view(LayoutMode::Horizontal, true);
		break;
	default:
		get_active_view()->key_input(ch);
	}
}

Window::~Window() {}
